<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="message">
    <button id="send-button">发送</button>

    <script>
        let websocket = new WebSocket("ws://127.0.0.1:8080/test");

        websocket.onopen = function() {
            // 连接建立完成后, 会自动执行到
            console.log("WebSocket 连接成功!");
        }

        websocket.onclose = function() {
            // 连接关闭后, 会自动执行到
            console.log("WebSocket 连接断开!");
        }

        websocket.onerror = function() {
            // 连接异常时, 会自动执行到
            console.log("WebSocket 连接异常!");
        }

        websocket.onmessage = function(e) {
            // 收到消息时, 自动执行
            console.log("WebSocket 收到消息! e:" + e.data);
        }

        let message = document.querySelector("#message");
        let sendButton = document.querySelector("#send-button");
        sendButton.onclick = function() {
            console.log("websocket 发送消息: " + message.value);
            websocket.send(message.value);
        }
    </script>
</body>
</html>